package com.tensequare.manager.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: Feng.Wang
 * @Company: Zelin.ShenZhen
 * @Description:
 * @Date: Create in 2019/3/30 15:38
 */
@Component
public class MangerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.得到当前请求的上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.得到请求对象
        HttpServletRequest request = currentContext.getRequest();
        //3.得到请求头对象
        String header = request.getHeader("Authorization");
        //放行
        if(request.getMethod().equals("OPTIONS")){return null;}
        if(request.getRequestURI().contains("/admin/login")){
            return null;
        }
        if(null != header && header.startsWith("Bearer ")){
            //取得token对象
            String token = header.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            //根据claims得到角色
            String roles = (String) claims.get("roles");
            if(null != roles && roles.equals("admin")){
                //重新放到zull的过滤器中
                currentContext.addZuulRequestHeader("Authorization",header);
                return null;
            }
        }
        currentContext.setSendZuulResponse(false);   //阻止过滤器执行
        currentContext.setResponseStatusCode(401);   //无权访问的状态码，也可是403
        currentContext.setResponseBody("无权访问");
        currentContext.getResponse().setContentType("text/html;charset=utf-8");
        return null;
    }
}
